package com.momoauth.common.mybatis.plugin;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ParameterUtils;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.sql.SQLException;

/**
 * 分页拦截器
 */
@Data
@NoArgsConstructor
public class MoMoPaginationInnerInterceptor extends PaginationInnerInterceptor {

    protected Long maxLimit = -1L; // 最大单页限制数量，-1为不受限制
    private DbType dbType = DbType.MARIADB;

    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        IPage<?> page = ParameterUtils.findPage(parameter).orElse(null);
        if (page != null && page.getSize() < 0) {
            page.setSize(0); //若size小于0时，重置为0，防止错误查询全表
        }
        super.beforeQuery(executor, ms, page, rowBounds, resultHandler, boundSql);
    }
}
